from django.http.response import JsonResponse
from django.shortcuts import redirect, render
from django.views import View
from .models import Cart
from user.models import User

from django.contrib.auth.mixins import LoginRequiredMixin


class CartListView(LoginRequiredMixin, View):
    login_url = '/signin/'
    redirect_field_name = 'next'

    def get(self, request):
        user_id = self.request.user.id
        trades = Cart.objects.filter(user_id=user_id, paid=False)
        count = trades.count()
        return render(
            request,
            'cart/list.html',
            {
                'trades': trades,
                'count': count
            }
        )


class AddToCartView(View):

    def get(self, request, book_id):
        if request.user.is_authenticated:
            Cart.objects.get_or_create(
                user_id=request.user.id,
                book_id=book_id,
                paid=False
            )
            return JsonResponse({'msg': f'{book_id}add to cart success!'}, status=200)
        else:
            return JsonResponse({'msg': 'Not login'}, status=403)


class RemoveFromCartView(View):

    def get(self, request, trade_id):
        if request.user.is_authenticated:
            Cart.objects.get(pk=trade_id).delete()
            return redirect('/cart/')
        else:
            return JsonResponse({'msg': 'Not login'}, status=403)


class CartPayView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:
            trades = Cart.objects.filter(user_id=user.id, paid=False)
            total_price = 0.0
            for trade in trades:
                total_price += trade.book.price

            if user.balance < total_price:
                return JsonResponse({'msg': 'Balance is not enough!'}, status=600)

            User.objects.filter(pk=user.id).update(
                balance=user.balance-total_price)
            trades.update(paid=True)
            return JsonResponse({'msg': 'Paid success!'}, status=200)
        else:
            return JsonResponse({'msg': 'Not login'}, status=403)
